package com.yellowpage.wf.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.yellowpage.white.dao.BaseDaoHibernateImpl;
import com.yellowpage.wf.data.WorkflowNode;

public class WorkflowNodeDaoImpl extends
		BaseDaoHibernateImpl<WorkflowNode, Long> implements WorkflowNodeDao {

	public WorkflowNodeDaoImpl() {
		super(WorkflowNode.class);
	}

	public void clearByWorkflowId(List ids) {
		String workflowIds = "";
		if (ids == null || ids.size() < 1)
			return;
		for (Iterator iterator = ids.iterator(); iterator.hasNext();) {
			Long workflowId = (Long) iterator.next();
			workflowIds += "," + workflowId.toString();
		}

		try {

			PreparedStatement ps = this.getConnection().prepareStatement(
					" delete from wf_workflow_node "
							+ " where workflow_id in ( "
							+ workflowIds.substring(1, workflowIds.length())
							+ " ) ");

			ps.execute();
		} catch (SQLException e) {
			this.logger.debug(this, e);
		}
	}
	
	public Map<String, String> copyWorkflowEntity(Long sourceWorkflowId, Long dimWorkflowId) {
		Map<String, String> pathNodeMap=new HashMap<String, String>();
		List <WorkflowNode>workflowNodeList=getAllWorkflowNodeByWorkflowId(sourceWorkflowId.toString());
		String [] nodeArray=new String[workflowNodeList.size()];
		for (int i = 0; i < workflowNodeList.size(); i++) {
			WorkflowNode workflowNode = workflowNodeList.get(i);
			nodeArray[i]=workflowNode.getWorkflowNodeId().toString();
			workflowNode.setWorkflowNodeId(null);
			workflowNode.setWorkflowId(dimWorkflowId);
		}
		this.save(workflowNodeList);
		for (int i = 0; i < nodeArray.length; i++) {
			pathNodeMap.put(nodeArray[i], workflowNodeList.get(i).getWorkflowNodeId().toString());
		}
		return pathNodeMap;
	}
	
	public WorkflowNode getWorkflowNodeByWorkflowIdAndType(String workflowId , String type) {
		List<WorkflowNode> nodeList = this.getObjectListByConditions(
				"from WorkflowNode w where w.workflowId = ? and w.type = ? ",
				new Object[] { workflowId , type});
		return nodeList.size() > 0 ? nodeList.get(0) : null;
	}
	
	public List<WorkflowNode> getAllWorkflowNodeByWorkflowId(String workflowId) {
		return this.getObjectListByConditions(
				"from WorkflowNode w where w.workflowId = ? ",
				new Object[] { workflowId });
	}

}